package emailbeans;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import dao.CandidateDAORemote;
import dao.EmployeeDAORemote;
import dto.CandidateDTO;
import dto.EmployeeDTO;

/**
 * This class build the message and send it to a specified tester if button send
 * is clicked.
 */

@ManagedBean
@SessionScoped
public class TesterEmailSender implements Serializable {

	private static final long serialVersionUID = 1L;

	private String id;

	private String from;
	private String message = null;
	private String subject = "MSG Candidates";
	private String smtpServ;
	private String email;

	@ManagedProperty(value = "#{tester}")
	EmployeeDTO tester ;
	List<CandidateDTO> candidates = new ArrayList<CandidateDTO>();

	public TesterEmailSender() {
		smtpServ = "msgc4i.msg.de";
	}

	/**
	 * Getter for employee. Employee DTO.
	 * 
	 * @return EmployeeDTO tester
	 */
	public EmployeeDTO getTester() {
		return tester;
	}

	/**
	 * Setter for EmployeeDTO tester.
	 * @param tester
	 */
	public void setTester(EmployeeDTO tester) {
		this.tester = tester;
	}

	/**
	 * Getters for candidates. List of candidateDTO.
	 * 
	 * @return
	 */

	public List<CandidateDTO> getCandidates() {
		return candidates;
	}

	/**
	 * Setter for List of candidates for one tester specified
	 * @param candidates
	 */
	public void setCandidates(List<CandidateDTO> candidates) {
		this.candidates = candidates;
	}

	/**
	 * Getters for id of tester.
	 * 
	 * @return
	 */
	public String getId() {
		return id;
	}
/**
 * Setter for id of tester.
 * @param id
 */
	public void setId(String id) {
		this.id = id;
	}

	/**
	 * Getter for address of sender
	 * @return
	 */
	public String getFrom() {
		return from;
	}

	/**
	 * Setter of addres of sender
	 * @param from
	 */
	public void setFrom(String from) {
		this.from = from;
	}

	/**
	 * Getters for message
	 * 
	 * @return built message
	 */
	public String getMessage() {

		return " Hello "
				+ this.getTester().getName()
				+ " !\n"
				+ " As a result of new applications for a new job in our company, we would like to prepare a test for these candidates: \n\n "
				+ constructCandidateList(this.getCandidates())
				+ "\n"
				+ "\n"
				+ "You will have to schedule an interview-test for every candidate for a specified date, time (hour:minutes) and location. \n"
				+ " Thank You! \n\n" + "MSG SYSTEMS ROMANIA \n\n ";
	}

	/**
	 * Setter for message.
	 * 
	 * @param message
	 */
	public void setMessage(String message) {
		this.message = message;
	}

	/**
	 * Getter for Subject.
	 * 
	 * @return
	 */
	public String getSubject() {
		return subject;
	}

	/**
	 * Setter of subject
	 * @param subject
	 */
	public void setSubject(String subject) {
		this.subject = subject;
	}

	/**
	 * Setter for Email address
	 * 
	 * @param email
	 */
	public void setEmail(String email) {
		this.email = email;
	}

	/**
	 * Get the tester email address from EmployeeDTO
	 * 
	 * @return
	 */
	public String getEmail() {
		return tester.getEmail();
	}

	/**
	 * Getters and Setters for Proxy.
	 * 
	 * @return
	 */
	public String getSmtpServ() {
		return smtpServ;
	}

	/** 
	 * Setter for proxy
	 * @param smtpServ
	 */
	public void setSmtpServ(String smtpServ) {
		this.smtpServ = smtpServ;
	}

	/**
	 * This method has one parameter: a list of CandidateDTO. It construct
	 * preatty print of a list. This method will be use to build the message.
	 * 
	 * @param list
	 * @return
	 */
	public String constructCandidateList(List<CandidateDTO> list) {
		String listString = "";
		for (int i = 0; i < list.size(); i++)
			listString = listString + "Name: " + list.get(i).getFirstName()
					+ list.get(i).getLastName() + "\n" + "Email: "
					+ list.get(i).getEmail() + "\n";

		return listString;

	}

	/**
	 * This method Authenticate the user to Msg Account, build the message and
	 * sent it to specified address.
	 * 
	 * @return
	 */
	public int sendEmail() {

		try {
			Properties props = System.getProperties();

			// -- Attaching to default Session, or we could start a new one --
			props.put("mail.transport.protocol", "smtp");
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.smtp.host", smtpServ);
			props.put("mail.smtp.auth", "true");

			Authenticator auth = new SMTPAuthenticator();

			Session session = Session.getInstance(props, auth);

			// -- Create a new message --
			Message msg = new MimeMessage(session);
			// -- Set the FROM and TO fields --
			// System.out.println(employeeBean.getEmail());
			msg.setFrom(new InternetAddress(from, "MSG Systems"));

			msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(
					email, false));

			msg.setSubject(subject);

			// -- Set some other header information --
			msg.setHeader("MyMail", "Mr. XYZ");
			msg.setSentDate(new Date());

			// create the message part
			MimeBodyPart messageBodyPart = new MimeBodyPart();
			// String fileAttachment = "Z:/Projects/Orders/PrimewJSP.7z";
			// fill message


			messageBodyPart.setText(message);

			Multipart multipart = new MimeMultipart();
			multipart.addBodyPart(messageBodyPart);

			// Put parts in message
			msg.setContent(multipart);

			// -- Send the message --
			Transport.send(msg);

			// write interview into the database

			try {
				FacesContext
						.getCurrentInstance()
						.getExternalContext()
						.redirect(
								"/MSGCandidateTesting/faces/alocateTesterUser.xhtml");
			} catch (IOException e) {
				e.printStackTrace();
			}

			return 0;
		} catch (Exception ex) {
			ex.printStackTrace();
			System.out.println("Exception " + ex);
			return -1;
		}
	}

	/**
	 * Method that redirect to previous page
	 */
	public void backFromSend() {
		// set buttons
		// redirect to testerhome
		try {
			FacesContext.getCurrentInstance().getExternalContext().redirect(
					"/MSGCandidateTesting/faces/alocateTesterUser.xhtml");
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * Inner Class that make the authentication on mail account.
	 * 
	 * @author vornicub
	 * 
	 */
	// Also include an inner class that is used for authentication purposes
	private class SMTPAuthenticator extends javax.mail.Authenticator {

		@Override
		public PasswordAuthentication getPasswordAuthentication() {
			String username = "vornicub"; // specify your email id here
			// (sender's email id)
			String password = "vornicub"; // specify your password here
			return new PasswordAuthentication(username, password);
		}
	}

}
